package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminMapper;
import com.heima.admin.service.AdminService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.admin.pojos.AdUser;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, AdUser> implements AdminService {
    @Override
    public ResponseResult Login(AdUserDto dto) {
        if (StringUtils.isNotBlank(dto.getName()) && StringUtils.isNotBlank(dto.getPassword())){
            AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
            if(adUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //通过用户登录时输入的密码  在加上 盐  组合 md5加密 总体对比
            String salt = adUser.getSalt(); //获取盐
            String dtoPassword = dto.getPassword(); //登录输入的密码
            //组合 md5加密
            if (!DigestUtils.md5DigestAsHex((dtoPassword+salt).getBytes()).equals(adUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //返回数据 只需要 token 和apuser对象

            Map<String , Object> map=new HashMap<>();
            map.put("token", AppJwtUtil.getToken(adUser.getId().longValue())); //工具类 通过id获取token
            adUser.setSalt("");
            adUser.setPassword("");
            map.put("user",adUser);
            return ResponseResult.okResult(map);
        }else {
            //Map<String , Object> map=new HashMap<>();
            //map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
    }
}
